package online.westonline.com.westonline.ui;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.easy.west.westclient.api.constacts.bean.HumanList;
import com.easy.west.westclient.api.constacts.bean.PersonBean;
import com.easy.west.westclient.api.constacts.event.QueryConstactsEvent;
import com.easy.west.westclient.api.department.bean.AllDepartMentBean;
import com.easy.west.westclient.api.department.bean.DepartMentBean;
import com.easy.west.westclient.api.department.bean.DepartMentList;
import com.easy.west.westclient.api.department.event.FindAllEvent;
import com.easy.west.westclient.api.department.event.QueryDepartMentEvent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import online.westonline.com.westonline.MyApplication;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.adapter.constacts.DepartMentAndConstactsAdpter;
import online.westonline.com.westonline.adapter.constacts.PopConstactAndDepartEmentAdpater;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.utils.CacheUtils;
import online.westonline.com.westonline.wedgit.RomateImageView;

/**
 * 通讯录界面
 */
public class ConstactsActivity extends BaseActivity {

    @BindView(R.id.recyclerView_constants)
    RecyclerView recyclerViewConstants;
    @BindView(R.id.tv_topbar_title)
    TextView tvTopbarTitle;
    @BindView(R.id.tv_topbar_title_center)
    TextView tvTopbarTitleCenter;
    @BindView(R.id.tv_topbar_menu)
    TextView tvTopbarMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.edit_search_department)
    EditText editSearchDepartment;
    @BindView(R.id.card_search)
    CardView cardSearch;
    @BindView(R.id.pro_constacts_search_state)
    ProgressBar proConstactsSearchState;
    @BindView(R.id.recyclerView_search)
    RecyclerView recyclerViewSearch;
    @BindView(R.id.ra_search_layout)
    RelativeLayout raSearchLayout;
    @BindView(R.id.tv_search_cancel)
    TextView tvSearchCancel;
    @BindView(R.id.img_toolbar_menu)
    RomateImageView imgToolbarMenu;
    private DepartMentAndConstactsAdpter departMentAndConstactsAdpter;
    private List<AllDepartMentBean.DataBean> dataBeanList = new ArrayList<>();
    private PopupWindow popupWindow;
    private String name;
    private List<DepartMentBean> departMentBeanList = new ArrayList<>();
    private List<PersonBean> personBeanList = new ArrayList<>();
    private PopConstactAndDepartEmentAdpater popConstactAndDepartEmentAdpater;


    @Override
    protected void initview() {
        //软键盘默认不弹出模式
        getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        toolbar.setTitle("通讯录");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        initpopwindow();
        initrecyclerview();
        initsession();
    }

    private void initsession() {
        //点击刷新
        imgToolbarMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!imgToolbarMenu.isStart())
                {
                    Snackbar.make(toolbar,"更新部门数据",Snackbar.LENGTH_SHORT).show();
                    imgToolbarMenu.setClickable(false);
                    imgToolbarMenu.show(true);
                    //请求所有部门
                    MyApplication.getClient().findalldepartMent();
                }

            }
        });
        //监听输入框变化
        editSearchDepartment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    name = s.toString();
                    departMentBeanList.clear();
                    personBeanList.clear();
                    Log.e("数量", "1：" + departMentBeanList.size() + "2:" + personBeanList.size());
                    //设置一下数据
                    popConstactAndDepartEmentAdpater.setDatas(personBeanList, departMentBeanList, name);
                    popConstactAndDepartEmentAdpater.notifyDataSetChanged();
                    recyclerViewSearch.removeAllViews();
                    proConstactsSearchState.setVisibility(View.VISIBLE);
                    raSearchLayout.setVisibility(View.VISIBLE);
                    recyclerViewConstants.setVisibility(View.GONE);
                    MyApplication.getClient().queryDepartment(name);
                } else {
                    raSearchLayout.setVisibility(View.GONE);
                    recyclerViewConstants.setVisibility(View.VISIBLE);
                }
            }
        });
        //点击取消
        tvSearchCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editSearchDepartment.setText("");
                raSearchLayout.setVisibility(View.GONE);
                departMentBeanList.clear();
                personBeanList.clear();
                popConstactAndDepartEmentAdpater.setDatas(personBeanList, departMentBeanList, name);
                popConstactAndDepartEmentAdpater.notifyDataSetChanged();
            }
        });
    }

    /**
     * 初始化搜索结果框
     */
    private void initpopwindow() {
        /*
        popConstactAndDepartEmentAdpater = new PopConstactAndDepartEmentAdpater();
        popView = View.inflate(this, R.layout.pop_search_window, null);
        ViewGroup.LayoutParams lp = cardSearch.getLayoutParams();
        recyclerView_search = popView.findViewById(R.id.recyclerView_pop_search);
        progressBar_searching = popView.findViewById(R.id.pro_constacts_search_state);
        recyclerView_search.setLayoutManager(new LinearLayoutManager(this));
        recyclerView_search.setAdapter(popConstactAndDepartEmentAdpater);
        popupWindow = new PopupWindow();
        popupWindow.setContentView(popView);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT-DensityUtils.dip2px(this,20));
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBrightness(ConstactsActivity.this, 1f);
            }
        });
        */


    }

    private void initrecyclerview() {

        departMentAndConstactsAdpter = new DepartMentAndConstactsAdpter();
        popConstactAndDepartEmentAdpater = new PopConstactAndDepartEmentAdpater();
        if (dataBeanList != null) {
            departMentAndConstactsAdpter.setData(dataBeanList);
        }
        recyclerViewConstants.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewConstants.setAdapter(departMentAndConstactsAdpter);
        recyclerViewSearch.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewSearch.setAdapter(popConstactAndDepartEmentAdpater);
    }

    @Override
    protected void initdata() {
        //先查询一次缓存
        dataBeanList = CacheUtils.getInstance().getAllDepatMent();
        if (dataBeanList != null) {
            if (dataBeanList.size() == 0) {
                imgToolbarMenu.show(true);
                //请求所有部门
                MyApplication.getClient().findalldepartMent();
            }
        } else {
            imgToolbarMenu.show(true);
            //请求所有部门
            MyApplication.getClient().findalldepartMent();
        }

    }

    @Override
    protected int setlayout() {
        return R.layout.activity_constacts;
    }

    /***
     * 查找所有的部门
     * @param allEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void findall(FindAllEvent allEvent) {
        dataBeanList = allEvent.getBean().getData();
        CacheUtils.getInstance().saveDepartMent(dataBeanList);
        departMentAndConstactsAdpter.setData(dataBeanList);
        departMentAndConstactsAdpter.notifyDataSetChanged();
        imgToolbarMenu.setClickable(true);
        imgToolbarMenu.show(false);
        Snackbar.make(toolbar,"部门数据更新完成",Snackbar.LENGTH_SHORT).show();
    }

    /***
     * 根据名称查找部门
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void queryDepartment(QueryDepartMentEvent eva) {
        if (eva.isOk()) {
            DepartMentList departMentList = eva.getBean();
            departMentBeanList = departMentList.getData();
            proConstactsSearchState.setVisibility(View.GONE);
            //前往查找联系人
            MyApplication.getClient().queryConstacts(name);
        }
    }

    /**
     * 查找名称符合的用户
     *
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void queryCosntacts(QueryConstactsEvent eva) {
        if (eva.isOk()) {
            HumanList humanList = eva.getBean();
            personBeanList = humanList.getData();
            popConstactAndDepartEmentAdpater.setDatas(personBeanList, departMentBeanList, name);
            popConstactAndDepartEmentAdpater.notifyDataSetChanged();
            proConstactsSearchState.setVisibility(View.GONE);
        }
    }

    /**
     * 设置亮度
     *
     * @param activity
     * @param brightness
     */
    public static void setBrightness(Activity activity, float brightness) {
        // Settings.System.putInt(activity.getContentResolver(),
        // Settings.System.SCREEN_BRIGHTNESS_MODE,
        // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = brightness;
        activity.getWindow().setAttributes(lp);
    }



}
